/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.asset.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import top.continew.admin.asset.mapper.CheckTaskMapper;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.starter.core.exception.BusinessException;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.query.SortQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.extension.crud.service.BaseServiceImpl;
import top.continew.admin.asset.mapper.CheckItemMapper;
import top.continew.admin.asset.model.entity.CheckItemDO;
import top.continew.admin.asset.model.query.CheckItemQuery;
import top.continew.admin.asset.model.req.CheckItemReq;
import top.continew.admin.asset.model.resp.CheckItemDetailResp;
import top.continew.admin.asset.model.resp.CheckItemResp;
import top.continew.admin.asset.service.CheckItemService;

/**
 * 盘点资产名单业务实现
 *
 * @author CharlieYan
 * @since 2025/07/11 16:31
 */
@Service
@RequiredArgsConstructor
public class CheckItemServiceImpl extends BaseServiceImpl<CheckItemMapper, CheckItemDO, CheckItemResp, CheckItemDetailResp, CheckItemQuery, CheckItemReq> implements CheckItemService {

    private final CheckTaskMapper checkTaskMapper;

    @Override
    public void export(CheckItemQuery query, SortQuery sortQuery, HttpServletResponse response) {
        super.export(query, sortQuery, response);
    }

    @Override
    public PageResp<CheckItemResp> page(CheckItemQuery query, PageQuery pageQuery) {
        QueryWrapper<CheckItemDO> queryWrapper = this.buildQueryWrapper(query);
        super.sort(queryWrapper, pageQuery);
        IPage<CheckItemDetailResp> page = baseMapper.selectCheckItemsPage(new Page<>(pageQuery.getPage(), pageQuery
            .getSize()), queryWrapper);
        PageResp<CheckItemResp> pageResp = PageResp.build(page, super.getListClass());
        pageResp.getList().forEach(this::fill);
        return pageResp;
    }

    @Override
    protected QueryWrapper<CheckItemDO> buildQueryWrapper(CheckItemQuery query) {
        String fuzzy = query.getFuzzy();
        Long taskId = query.getTaskId();
        return new QueryWrapper<CheckItemDO>().eq("tt.task_id", taskId)
            .and(StrUtil.isNotBlank(fuzzy), q -> q.like("tt.name", fuzzy)
                .or()
                .like("tt.code", fuzzy)
                .or()
                .like("tt.sn", fuzzy));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(CheckItemReq req, Long id) {
        req.setCheckerId(UserContextHolder.getUserId());
        // 1. 更新盘点项表
        super.update(req, id);

        // 2. 安全获取任务ID（处理空指针）
        CheckItemDetailResp checkItem = super.get(id);
        if (req == null || checkItem == null) {
            throw new IllegalArgumentException("更新任务ID不能为空");
        }
        Long taskId = checkItem.getTaskId();

        // 3. 优化查询：仅查询必要字段
        Integer notChecked = checkTaskMapper.selectNotCheckedCount(taskId);

        if (notChecked == null) {
            throw new BusinessException("盘点任务不存在: " + taskId);
        }

        // 4. 优化更新：使用条件更新避免全字段更新+状态校验
        if (notChecked == 0) {
            // 仅当任务处于未完成状态时才更新（假设1表示进行中）
            int affectedRows = checkTaskMapper.updateCheckTaskStatus(taskId, 2);
            log.debug("更新任务状态影响行数: {" + affectedRows + "}");
        }
    }

}